package com.demo.springmvc底层演示.demo1;

import javax.servlet.http.HttpServletResponse;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.yaml.snakeyaml.Yaml;

/**返回值处理器
 * @author sulei_zhang
 *
 */
public class YmlReturnValueHandler implements HandlerMethodReturnValueHandler {

	@Override
	public boolean supportsReturnType(MethodParameter returnType) {
		Yml yml = returnType.getMethodAnnotation(Yml.class);
		return yml != null;
	}

	@Override
	public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest) throws Exception {
		String str = new Yaml().dump(returnValue);
		HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
		response.setContentType("text/plain;charset=utf-8");
		response.getWriter().print(str);
		// 设置请求已经处理完毕
		mavContainer.setRequestHandled(true);
	}

}
